package main

import (
	"GinStandardTemplate/config"
	"GinStandardTemplate/utils/database"
	"GinStandardTemplate/utils/logger"
	"path/filepath"
	"time"

	"go.uber.org/zap"
	"gorm.io/gen"
)

func init() {
	// 初始化全局配置
	config.InitGlobalConfigAndLog()
	defer func() {
		_ = logger.Logger.Sync()
	}()

	// 初始化数据库
	dsn, err := database.BuildDSN(database.DSNConfig{
		Dialect:    config.GlobalConfig.Database.Dialect,
		Host:       config.GlobalConfig.Database.Host,
		Port:       config.GlobalConfig.Database.Port,
		User:       config.GlobalConfig.Database.Username,
		Password:   config.GlobalConfig.Database.Password,
		DBName:     config.GlobalConfig.Database.DBName,
		Charset:    config.GlobalConfig.Database.Charset,
		SSLMode:    config.GlobalConfig.Database.SSLMode,
		TimeZone:   config.GlobalConfig.Database.TimeZone,
		SQLiteFile: config.GlobalConfig.Database.SQLiteFile,
	})
	if err != nil {
		logger.Logger.Fatal("构建数据库连接地址失败", zap.Error(err))
	}
	if err := database.InitDB(logger.Logger, database.DBConfig{
		Dialect:      config.GlobalConfig.Database.Dialect,
		DSN:          dsn,
		SQLiteFile:   config.GlobalConfig.Database.SQLiteFile,
		LogLevel:     config.GlobalConfig.Database.GormLogLevel,
		MaxIdleConns: config.GlobalConfig.Database.MaxIdleConns,
		MaxOpenConns: config.GlobalConfig.Database.MaxOpenConns,
		ConnMaxLife:  time.Duration(config.GlobalConfig.Database.ConnMaxLifetime) * time.Minute,
		InitTimeout:  time.Duration(config.GlobalConfig.Database.InitTimeout) * time.Second,
	}); err != nil {
		logger.Logger.Fatal("数据库初始化失败", zap.Error(err))
	}
}

// GenerateModels
//
//	@Description: 生成模型文件
func GenerateModels() {
	// 初始化生成器
	g := gen.NewGenerator(gen.Config{
		OutPath:      filepath.Join(config.GlobalConfig.Path.BaseDir, "internal", "repository"), // 数据访问层（CRUD代码）
		ModelPkgPath: filepath.Join(config.GlobalConfig.Path.BaseDir, "internal", "model"),      // 模型层（结构体定义）
		Mode:         gen.WithoutContext | gen.WithDefaultQuery | gen.WithQueryInterface,
	})

	if database.DB == nil {
		logger.Logger.Fatal("数据库连接失败")
	}

	g.UseDB(database.DB)

	// 自动生成所有表的模型
	tables := g.GenerateAllTable()
	// 所有表绑定基础查询方法
	g.ApplyBasic(tables...)

	// 执行生成操作
	g.Execute()
	logger.Logger.Info("生成数据库模型成功")
}

func main() {
	GenerateModels()
}
